package com.example.gbuffer.Utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileUtil {
    private final static String LOG_TAG = "FileUtil";
    public static String readFileFromAssets(Context context, String fileName) {

        if ( !doesFileExistInAssets(context, fileName)) {
            Log.e(LOG_TAG, "file (" + fileName +") doesn't exist.");
            return "";
        }

        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStream inputStream = context.getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static boolean doesFileExistInAssets(Context context, String fileName) {
        AssetManager assetManager = context.getAssets();
        try {
            // 尝试打开文件
            String[] files = assetManager.list(""); // 获取 assets 目录下的文件列表
            for (String file : files) {
                if (file.equals(fileName)) {
                    return true; // 文件存在
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false; // 文件不存在
    }
}